//
//  TranslationVC.m
//  语音翻译合成Demo
//
//  Created by 王鹏宇 on 2018/2/26.
//  Copyright © 2018年 王鹏宇. All rights reserved.
//


#import "TranslationVC.h"

#import <Speech/Speech.h>
#import <AVFoundation/AVFoundation.h>

#import <CommonCrypto/CommonDigest.h>
#import "TranslateLeftCell.h"
#import "TranslateRightCell.h"
#import "SelectViewController.h"
#import <AFNetworking.h>
#import "TranslationModel.h"
#import "LanguageModel.h"
#import <IQKeyboardManager.h>
#import "RippleView.h"
#define kDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]

#define RecordViewWidth 300 * kScreenWidth/375
#import "IGAvPlayerManager.h"
@interface TranslationVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,TranslateCellDelegate>

@property (weak, nonatomic) IBOutlet UIButton *languageBtnLeft;

@property (weak, nonatomic) IBOutlet UILabel *leftLabel;
@property (weak, nonatomic) IBOutlet UILabel *rightLabel;

@property (weak, nonatomic) IBOutlet UIButton *languageBtnRight;

@property (weak, nonatomic) IBOutlet UIButton *exchangeBtn;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIButton *recordBtnLeft;

@property (weak, nonatomic) IBOutlet UIButton *recordBtnRight;

@property (weak, nonatomic) IBOutlet UILabel *tipLabel;

@property (weak, nonatomic) IBOutlet UIView *inputView;

@property (weak, nonatomic) IBOutlet UITextField *textFiled;

@property (weak, nonatomic) IBOutlet UIButton *inputLeftBtn;

@property (weak, nonatomic) IBOutlet UIButton *inputRightBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewLeftSpace;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewRightSpace;

@property (nonatomic, strong) UIView *recordView;

@property (nonatomic, strong) UILabel *recordTipLabel;

@property (nonatomic, strong) RippleView *recordAnimationView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewBottomSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *selectViewTopSpace;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *recordViewWidth;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *animationViewWidth;

// 辅助属性
@property (nonatomic, copy) NSString *language1;//语音识别 左
@property (nonatomic, copy) NSString *language2;//语音识别 右

@property (nonatomic, copy) NSString *speechLanguage;//语音合成语言
@property (nonatomic, copy) NSString *language;//要翻译语言
@property (nonatomic, copy) NSString *translate;//翻译目标语言

@property (nonatomic, strong)LanguageModel *langModel1;
@property (nonatomic, strong)LanguageModel *langModel2;

// 录音
@property (nonatomic, strong) AVAudioRecorder *recorder;

// 语音合成
@property (nonatomic, strong) AVSpeechSynthesizer *synthesizer;
@property (nonatomic, strong) AVSpeechSynthesisVoice *voice;

@property (nonatomic, strong)NSMutableArray *dataSoure;

@property (nonatomic, strong)TranslationModel *model;

@property (nonatomic, strong)UIView * maskView;

@property (nonatomic, assign)BOOL isRecording;
@end

@implementation TranslationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[IGAvPlayerManager shareManeger] stop];
    
    self.inputView.hidden = YES;
    self.inputViewBottomSpace.constant = -60;
    self.selectViewTopSpace.constant = kNavigationBarHeight;
    
    [self setup];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
    [audioSession setActive:YES error:nil];
    
    [audioSession requestRecordPermission:^(BOOL granted) {
        
    }];
    
    
    [self initAuth];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
}


- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    if (self.dataSoure.count > 1) {
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:self.dataSoure.count - 1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
   
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [AppManager sharedManager].translationArray = self.dataSoure;
    [AppManager sharedManager].languageLeft = self.langModel1;
    [AppManager sharedManager].languageRight = self.langModel2;
    
}

- (void)initAuth {
    
    if (@available(iOS 10.0, *)) {
        [SFSpeechRecognizer  requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {}];
    } else {
       
    }
}

- (UIView *)maskView{
    if (!_maskView) {
        _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 140)];
        _maskView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        
        [_maskView addSubview:self.recordView];
        self.recordView.center = _maskView.center;
    }
    return _maskView;
}

- (UIView *)recordView {
    if (!_recordView) {
        
        _recordView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, RecordViewWidth, RecordViewWidth/3 *2)];
        _recordView.layer.cornerRadius = 5;
        _recordView.clipsToBounds = YES;
        _recordView.backgroundColor = [UIColor whiteColor];
        _recordAnimationView = [[RippleView alloc] initWithFrame:CGRectMake(0, 0, Width, Width)];
        [_recordView addSubview:_recordAnimationView];
        _recordAnimationView.center = CGPointMake(_recordView.centerX, _recordView.centerY - 25);
        
        UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"translation麦克"]];
        [_recordAnimationView addSubview:imageView];
        imageView.center = CGPointMake(Width/2,Width/2);
        
        _recordTipLabel = [[UILabel alloc] init];
        _recordTipLabel.textColor = kThemeColor;
        _recordTipLabel.font = Font(14);
        _recordTipLabel.textAlignment = NSTextAlignmentCenter;
        _recordTipLabel.text = MYLocalizedString(@"TRANSLATION_UP_TIP", nil);
        [_recordView addSubview:_recordTipLabel];
        
        [_recordTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_recordAnimationView.mas_bottom);
            make.bottom.equalTo(_recordView.mas_bottom).offset(-10);
            make.leading.equalTo(_recordView.mas_leading).offset(10);
            make.trailing.equalTo(_recordView.mas_trailing).offset(-10);
        }];
    }
    
    return _recordView;
}
- (NSMutableArray *)dataSoure {
    
    if (!_dataSoure) {
        
        if ([AppManager sharedManager].translationArray) {
            _dataSoure = [NSMutableArray arrayWithArray:[AppManager sharedManager].translationArray];
        }else{
            _dataSoure = [[NSMutableArray alloc] init];
        }
        
    }
    return _dataSoure;
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
- (void)setLangModel1:(LanguageModel *)langModel1{
    _langModel1 = langModel1;
    self.language1 = langModel1.lang;
    self.leftLabel.text = MYLocalizedString(langModel1.name, nil);
    [self.recordBtnLeft setTitle:MYLocalizedString(langModel1.name, nil) forState:UIControlStateNormal];
}

- (void)setLangModel2:(LanguageModel *)langModel2{
    _langModel2 = langModel2;
    self.language2 = langModel2.lang;
    self.rightLabel.text =MYLocalizedString(langModel2.name, nil);
    [self.recordBtnRight setTitle:MYLocalizedString(langModel2.name, nil) forState:UIControlStateNormal];
}

- (void)setup {
    
    self.title = MYLocalizedString(@"TRANSLATION_NAME", nil);
    self.tipLabel.text = MYLocalizedString(@"TRANSLATION_PRESS", nil);
    self.textFiled.delegate = self;
    self.textFiled.returnKeyType = UIReturnKeySend;
    self.textFiled.placeholder = MYLocalizedString(@"TRANSLATION_PLACEHOLDER", nil);
    
    self.leftLabel.font = Font(14);
    self.rightLabel.font = Font(14);
    self.leftLabel.textColor = kSubitleColor;
    self.rightLabel.textColor = kSubitleColor;
    [self.recordBtnLeft setBackgroundColor:kThemeColor];
    [self.recordBtnRight setBackgroundColor:kThemeRedColor];
    self.recordBtnLeft.titleLabel.numberOfLines = 0;
    self.recordBtnLeft.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.recordBtnRight.titleLabel.numberOfLines = 0;
    self.recordBtnRight.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.languageBtnLeft setTitleColor:kSubitleColor forState:UIControlStateNormal];
    [self.languageBtnRight setTitleColor:kSubitleColor forState:UIControlStateNormal];
    self.tipLabel.textColor = kContentColor;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TranslateLeftCell" bundle:nil] forCellReuseIdentifier:@"TranslateLeftCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TranslateRightCell" bundle:nil] forCellReuseIdentifier:@"TranslateRightCell"];
    
    [self rightBarButtonWithImageName:@"删除" selector:@selector(deleteHistory)];
    //注册键盘弹出通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    
    self.langModel1 = [AppManager sharedManager].languageLeft;
    self.langModel2 = [AppManager sharedManager].languageRight;
    self.model = [[TranslationModel alloc] init];
}


- (IBAction)LanguageLeftBtnClicked:(UIButton *)sender {
    
    [self.textFiled endEditing:YES];
    SelectViewController *vc =  [[SelectViewController alloc] init];
    vc.type = 1;
    vc.block = ^(LanguageModel *lang){
       
        self.langModel1 = lang;
       
    };
    vc.currentLanguage = self.language1;
    vc.seletedLanguagel = self.language2;
    [self.navigationController pushViewController:vc animated:YES];
}


- (IBAction)languageRightBtnClicked:(UIButton *)sender {
    [self.textFiled endEditing:YES];
    SelectViewController *vc =  [[SelectViewController alloc] init];
    vc.type = 2;
    vc.block = ^(LanguageModel *lang) {
        self.langModel2 = lang;
    };
    vc.currentLanguage = self.language2;
    vc.seletedLanguagel = self.language1;
    [self.navigationController pushViewController:vc animated:YES];
}


- (IBAction)inputLanguageBtnLeftClicked:(UIButton *)sender {
    
    self.language = self.langModel1.translation;
    self.translate = self.langModel2.translation;
    self.inputViewLeftSpace.constant = 60;
    self.inputViewRightSpace.constant = 20;
    [self.textFiled becomeFirstResponder];
    self.model.directionNum = 1;
    self.model.languageType = self.language1;
    self.model.languageName = self.langModel1.name;
    self.speechLanguage = self.language2;
}

- (IBAction)inputLanguageBtnRightClicked:(id)sender {
    
    self.language = self.langModel2.translation;
    self.translate = self.langModel1.translation;
    
    self.inputViewLeftSpace.constant = 20;
    self.inputViewRightSpace.constant = 60;
    [self.textFiled becomeFirstResponder];
    self.speechLanguage = self.language1;
    self.model.languageType = self.language2;
    self.model.languageName = self.langModel2.name;
    self.model.directionNum = 2;
}
- (IBAction)touchDownRecordLft:(UIButton *)sender {
    
    if (!_isRecording) {
        self.language = self.langModel1.translation;
        self.translate = self.langModel2.translation;
        self.model.languageName = self.langModel1.name;
        
        [self record];
        [self startAnimation];
        self.tipLabel.text = MYLocalizedString(@"TRANSLATION_STOP", nil);
        [self.recordBtnLeft setBackgroundColor:UIColorHex(#01A1C5)];
        _recordTipLabel.text = MYLocalizedString(@"TRANSLATION_UP_TIP", nil);
        self.isRecording = YES;
    }
    
   
}



- (IBAction)leftCancel:(UIButton *)sender {
    self.tipLabel.text = MYLocalizedString(@"TRANSLATION_PRESS", nil);
    [self.recorder stop];
    [self stopAnimation];
    _recordTipLabel.text = MYLocalizedString(@"TRANSLATION_EXIT_TIP", nil);
    [self.recordBtnLeft setBackgroundColor:kThemeColor];
}



- (IBAction)rightCancel:(UIButton *)sender {
    
    self.tipLabel.text = MYLocalizedString(@"TRANSLATION_PRESS", nil);
    _recordTipLabel.text = MYLocalizedString(@"TRANSLATION_EXIT_TIP", nil);
    [self.recordBtnRight setBackgroundColor:kThemeRedColor];
    [self.recorder stop];
    [self stopAnimation];
}

- (IBAction)recordBtnLeftCliked:(UIButton *)sender {
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.recordBtnLeft.userInteractionEnabled = YES;
    });
    self.model.directionNum = 1;
    self.speechLanguage = self.language2;
    self.model.languageType = self.language1;
    [self speechRecognitionWithLanguage:self.language1];
    [self stopAnimation];
    self.tipLabel.text = MYLocalizedString(@"TRANSLATION_PRESS", nil);
    [self.recordBtnLeft setBackgroundColor:kThemeColor];
    self.isRecording = NO;
    self.recordBtnLeft.userInteractionEnabled = NO;
}


- (IBAction)touchDownRecordRight:(UIButton *)sender {
    
    if (!_isRecording) {
        self.language = self.langModel2.translation;
        self.translate = self.langModel1.translation;
        self.model.languageName = self.langModel2.name;
        [self record];
        [self startAnimation];
        self.tipLabel.text = MYLocalizedString(@"TRANSLATION_STOP", nil);
        [self.recordBtnRight setBackgroundColor:UIColorHex(#BF3850)];
        _recordTipLabel.text = MYLocalizedString(@"TRANSLATION_UP_TIP", nil);
        self.isRecording = YES;
    }
    
}

- (IBAction)recordBtnRightClicked:(UIButton *)sender {
    
    self.recordBtnRight.userInteractionEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       self.recordBtnRight.userInteractionEnabled = YES;
    });
    self.speechLanguage = self.language1;
    self.model.languageType = self.language2;
    [self speechRecognitionWithLanguage:self.language2];
    self.model.directionNum = 2;
    [self stopAnimation];
    self.tipLabel.text = MYLocalizedString(@"TRANSLATION_PRESS", nil);
    [self.recordBtnRight setBackgroundColor:kThemeRedColor];
    
    self.isRecording = NO;
}

- (IBAction)hideKeyBorad:(UIButton *)sender {
    
    [self.textFiled endEditing:YES];
    
}
- (IBAction)exchangeLanguage:(UIButton *)sender {
    [self.textFiled endEditing:YES];
    LanguageModel * model = self.langModel1;
    self.langModel1 = self.langModel2;
    self.langModel2 = model;
}

- (void)deleteHistory {
    
    [IGAlertView alertWithTitle:nil message:MYLocalizedString(@"TRANSLATION_DELETE", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"MYDOWNLOAD_DELETE_COMMIT", nil) commit:^{
        [self.dataSoure removeAllObjects];
        [self.tableView reloadData];
        
    } cancel:nil];
}

- (NSDictionary *)getAudioSetting {
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    
    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    [dicM setObject:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [dicM setObject:@(2) forKey:AVNumberOfChannelsKey];
    [dicM setObject:@(32) forKey:AVLinearPCMBitDepthKey];
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    [dicM setObject:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    [dicM setObject:@(256000) forKey:AVEncoderBitRateKey];
    
    return dicM;
}


#pragma mark  -- TranslateCellDelegate

- (void)playTheSpeech:(NSString *)str Translation:(NSString *)translationType {
    
    [self speechSynthesisString:str ToLanguage:translationType];
}



- (void)startAnimation {
    
    self.maskView.hidden = NO;
    [[UIApplication sharedApplication].keyWindow addSubview:self.maskView];
    [self.recordAnimationView startAnimation];
}

- (void)stopAnimation {
    
     self.maskView.hidden = YES;
    [self.maskView removeFromSuperview];
    [self.recordAnimationView stopAnimation];
}
#pragma mark  -- 功能

//录音功能
- (void)record{
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/file.caf", kDocumentPath];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:urlStr]) {
        [[NSFileManager defaultManager] removeItemAtPath:urlStr error:nil];
    }
    
    NSError *error;
    NSURL *url = [NSURL fileURLWithPath:urlStr];
    NSDictionary *setting = [self getAudioSetting];
    self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:&error];
    if (error) {
        NSLog(@"error:%@", error);
        return;
    }
    
    self.recorder.meteringEnabled = YES;
    [self.recorder prepareToRecord];
    [self.recorder record];
}

//语音识别成文字
- (void)speechRecognitionWithLanguage:(NSString *)language{
    
    
    [self.recorder pause];
    NSLocale *local =[[NSLocale alloc] initWithLocaleIdentifier:language];
    if (@available(iOS 10.0, *)) {
        SFSpeechRecognizer *localRecognizer =[[SFSpeechRecognizer alloc] initWithLocale:local];
        
        NSURL *url = [NSURL fileURLWithPath: [NSString stringWithFormat:@"%@/file.caf", kDocumentPath]];
        
        if (!url) return;
        SFSpeechURLRecognitionRequest *res =[[SFSpeechURLRecognitionRequest alloc] initWithURL:url];
        res.shouldReportPartialResults = NO;
        // __weak typeof(self) weakSelf = self;
        [localRecognizer recognitionTaskWithRequest:res resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
            if (error) {
                
               // [IGUtil showToast:MYLocalizedString(@"TRANSLATION_SPEECH_FAIL", nil)];
                NSLog(@"语音识别解析失败,%@", error);
            }else {
                //result.bestTranscription.formattedString;//语音识别文字
                
                
                //            if (res.shouldReportPartialResults) {
                //                NSLog(@"dddddd");
                //            }
                
                [self translateLanguage1:self.language ToLanguage2:self.translate WithString:result.bestTranscription.formattedString];
            }
        }];
    } else {
        [IGUtil showToast:@"系统版本不支持"];
    }
}

//文字翻译调用的是百度接口

- (void)translateLanguage1:(NSString *)langguage1 ToLanguage2:(NSString *)language2 WithString:(NSString *)string {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    //    param[@"q"] = @"apple";
    //    param[@"from"] = @"en";
    //    param[@"to"] = @"zh";
    //    param[@"appid"] = @"20171205000102273";
    //    param[@"salt"] = @"123";
    //    param[@"sign"] = @"9e4e8603b30cc82172a92b46b8526fda";
    
    NSString *sign = [NSString stringWithFormat:@"20171205000102273%@123qSus3KPbUHmyf3FboYVM", string];
    [self xq_md5:sign];
    
    NSString *url = [NSString stringWithFormat:@"http://api.fanyi.baidu.com/api/trans/vip/translate?q=%@&from=%@&to=%@&appid=20171205000102273&salt=123&sign=%@", string, langguage1, language2, [self xq_md5:sign]];
    NSString *utf = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//NSUTF8StringEncoding
    NSLog(@"url:%@", url);
    self.model.languageStr = string;
    self.tipLabel.text = MYLocalizedString(@"TRANSLATION_TRANSLATING", nil);
    [ActivityIndicatorView showHUDAddedTo:self.tableView];
    [manager GET:utf parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *err;
        id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&err];
        NSLog(@"result:%@", json);
       
        NSString * str = json[@"trans_result"][0][@"dst"];
        TranslationModel * model = [[TranslationModel alloc] init];
        model.languageStr = self.model.languageStr;
        model.translationStr = str;
        model.directionNum = self.model.directionNum;
        model.toLanguageType = self.speechLanguage;
        model.languageType = self.model.languageType;
        model.languageName = self.model.languageName;
        [ActivityIndicatorView hideHUDAddedTo:self.tableView];
        self.tipLabel.text = MYLocalizedString(@"TRANSLATION_PRESS", nil);
        [self.dataSoure addObject:model];
        [self.tableView reloadData];
        [self speechSynthesisString:str ToLanguage:self.speechLanguage];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.dataSoure.count > 1) {
                NSIndexPath * indexPath = [NSIndexPath indexPathForRow:self.dataSoure.count - 1 inSection:0];
                [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            }
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [IGUtil showToast:MYLocalizedString(@"TRANSLATION_TRANSLATE_FAIL", nil)];
        self.tipLabel.text = MYLocalizedString(@"TRANSLATION_PRESS", nil);
    }];
}

// 根据文字语音合成

- (void)speechSynthesisString:(NSString *)string  ToLanguage:(NSString *)language{
    
    self.voice = [AVSpeechSynthesisVoice voiceWithLanguage:language];
    self.synthesizer = [[AVSpeechSynthesizer alloc] init];
    
        AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:string];
        utterance.voice = self.voice;
        [self.synthesizer speakUtterance:utterance];
   
//        [self.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryWord];

}
#pragma mark  -- UITableViewDataSource,UITableViewDelegate


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSoure.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TranslationModel * model = self.dataSoure[indexPath.row];
    
    if (model.directionNum == 1) {
        
        TranslateLeftCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TranslateLeftCell"];
        cell.delegate = self;
        [cell configData:model];
        return cell;
    }else{
        TranslateRightCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TranslateRightCell"];
        cell.delegate = self;
        [cell configData:model];
        return cell;
    }
    return nil;
}


#pragma mark  -- UITextFieldDelegate


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField endEditing:YES];
    NSString *  str = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (str.length > 0) {
        [self translateLanguage1:self.language ToLanguage2:self.translate WithString:textField.text];
    }
    
    
    return YES;
}

#pragma mark   键盘弹出

- (void)keyboardWillShow:(NSNotification *)note {
    
    NSDictionary *info = [note userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    self.inputView.hidden = NO;
    self.inputViewBottomSpace.constant =keyboardSize.height;
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
    
}

- (void)keyboardWillHide:(NSNotification *)note {
    
    self.inputViewBottomSpace.constant = -60;
    
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.inputView.hidden = YES;
    }];

}




- (NSString *)xq_md5:(NSString *)str {
    const char *cStr = [str UTF8String];//转换成utf-8
    
    unsigned char result[16];//开辟一个16字节（128位：md5加密出来就是128位/bit）的空间（一个字节=8字位=8个二进制数）
    
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result);
    /*
     extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md)官方封装好的加密方法
     把cStr字符串转换成了32位的16进制数列（这个过程不可逆转） 存储到了result这个空间中
     */
    
    return  [[NSString stringWithFormat:
              
              @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
              
              result[0], result[1], result[2], result[3],
              
              result[4], result[5], result[6], result[7],
              
              result[8], result[9], result[10], result[11],
              
              result[12], result[13], result[14], result[15]
              
              ] lowercaseString];
    
    /*
     x表示十六进制，%02X  意思是不足两位将用0补齐，如果多余两位则不影响
     
     NSLog("%02X", 0x888);  //888
     
     NSLog("%02X", 0x4); //04
     */
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
